#include "send_command.h"

/*
 *command 要求是处理好的命令
 *eg:用户输入<mkdir    cpp>--->处理--->cmd=<mkdir>
 *								 --->command=<mkdir cpp>
 *
 */
void send_command(int sock, const char *command, const char *user_name, const char *virtual_path, const char *additional)
{
    uint32_t cmd_len = htonl(strlen(command));
    uint32_t name_len = htonl(strlen(user_name));
    uint32_t path_len = htonl(strlen(virtual_path));
    uint32_t add_len = additional ? htonl(strlen(additional)) : 0;
    size_t total_len = 12 + strlen(command) + strlen(user_name) + strlen(virtual_path) + (additional ? 4 + strlen(additional) : 0);
    char *message = (char *)malloc(total_len);
    if (!message)
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    memcpy(message, &cmd_len, 4);
    memcpy(message + 4, command, strlen(command));
    memcpy(message + 4 + strlen(command), &name_len, 4);
    memcpy(message + 8 + strlen(command), user_name, strlen(user_name));
    memcpy(message + 8 + strlen(command) + strlen(user_name), &path_len, 4);
    memcpy(message + 12 + strlen(command) + strlen(user_name), virtual_path, strlen(virtual_path));
    if (additional)
    {
        memcpy(message + 12 + strlen(command) + strlen(user_name) + strlen(virtual_path), &add_len, 4);
        memcpy(message + 16 + strlen(command) + strlen(user_name) + strlen(virtual_path), additional, strlen(additional));
    }
 
    if (send(sock, message, total_len, 0) < 0)
    {
        perror("send");
        free(message);
        close(sock);
        exit(EXIT_FAILURE);
    }
    
    free(message);
}
